import { useGlobalStore } from "@/store/modules";
import { DEFAULT_PRIMARY } from "@/config/config";
import { Theme } from "./interface"
import { getLightColor, getDarkColor } from '@/utils/color'
import { asideTheme, menuTheme, headerTheme } from "@/styles/theme";

/**
 * @description 全局主题 hooks
 * */
export const useTheme = () => {
    const globalStore = useGlobalStore();
    const { primary, isDark } = storeToRefs(globalStore);

    // 切换暗黑模式 ==> 同时修改主题颜色、侧边栏、头部颜色
    const switchDark = () => {
        const html = document.documentElement as HTMLElement;
        if (isDark.value) html.setAttribute("class", "dark")
        else html.setAttribute("class", "")
        changePrimary(primary.value);
        setAsideTheme();
        setHeaderTheme();
    }


    const changePrimary = (val: string | null) => {
        if (!val) {
            val = DEFAULT_PRIMARY;
            ElMessage({ type: "success", message: `主题颜色已重置为 ${DEFAULT_PRIMARY}` });
        }
        // 计算主题颜色变化
        document.documentElement.style.setProperty("--el-color-primary", val);
        document.documentElement.style.setProperty(
            "--el-color-primary-dark-2",
            isDark.value ? `${getLightColor(val, 0.2)}` : `${getDarkColor(val, 0.3)}`
        );
        for (let i = 1; i <= 9; i++) {
            const primaryColor = isDark.value ? `${getDarkColor(val, i / 10)}` : `${getLightColor(val, i / 10)}`;
            document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, primaryColor);
        }
        globalStore.setGlobalState("primary", val);
    }

    const setMenuTheme = () => {
        let type: Theme.ThemeType = "light";
        if (isDark.value) type = "dark";
        const theme = menuTheme[type!];
        for (const [key, value] of Object.entries(theme)) {
            document.documentElement.style.setProperty(key, value);
        }
    }

    const setAsideTheme = () => {
        let type: Theme.ThemeType = "light"
        if (isDark.value) type = 'dark'
        const theme = asideTheme[type!];
        for (const [key, value] of Object.entries(theme)) {
            document.documentElement.style.setProperty(key, value);
        }
        setMenuTheme();
    }

    const setHeaderTheme = () => {
        let type: Theme.ThemeType = "light";
        if (isDark.value) type = "dark";
        const theme = headerTheme[type!];
        for (const [key, value] of Object.entries(theme)) {
            document.documentElement.style.setProperty(key, value);
        }
        setMenuTheme();
    }

    const initTheme = () => {
        switchDark();
    }

    return {
        initTheme,
        switchDark,
        setAsideTheme,
        changePrimary
    }
}

